 
var wallet =  require('../../wallet.js')
var chance = require('../../../utils/chancenet.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num:0,
    linkman: '',// 联系人
    linkaddress:'',//地址
    linkicon:'',//币
    linkcomment:'',//备注
    transMon:0, //0 不转账 1转账
    textList: [1, 2, 3, 4, 5, 6],
    fadeIn:false,
    affirmLang:{},
    coinMess:{},
    //address:'',
    coinData:{},
    money:0,
    sliderSpeed:'',
    current:'',
    linkaddress:'',
    qrCode:'',//扫二维码，btc地址
    //transferAccounts:'',//转出币
    changeFee:'',
    coinNumber:1,//输入币的数量
    payPSWD:"",//支付密码
    aginpswd:'',
    lang:'',//语言
    linkPer:'',
    goaddreFlag:true,
    defaultVal:0,
    chainId: chance.chainId//1,主网;3,测试网
    // userAddre:''//btc地址
  },
  getmoneyData(type){//eth接口
    var token = wx.getStorageSync('createUser').access_token; 
    var addr = wx.getStorageSync('addressETH');
    var $this = this;
    let money = $this.data.money || 1
     wallet.post('transaction/prepare', { access_token: token, coin_symbol: type, wallet_addr:addr},function(res){
        console.log(res)
        $this.setData({
          coinData:res.data,
          money: money*res.data.exchange_rate,
          sliderSpeed: ((res.data.current - res.data.low )/(res.data.high - res.data.low))*100,
          current: res.data.current,
          defaultVal:1
        })
    }) 
  },
  getBTCData(type){//btc
    var token = wx.getStorageSync('createUser').access_token;
    var addr = wx.getStorageSync('addressBTC');
    var $this = this;
    let money = $this.data.money || 1
    wallet.post('transactionbtc/prepare', { access_token: token, coin_symbol: type, wallet_addr: addr }, function (res) {
  
      $this.setData({
        money:money*res.data.exchange_rate,
        coinData:res.data,
        sliderSpeed: ((res.data.current - res.data.low) / (res.data.high - res.data.low)) * 100,
        current: res.data.current,
        defaultVal:1
      })
    })
  },
  tokenCoin(type){//代币参数
    this.setData({
      goaddreFlag:false
    })
    var token = wx.getStorageSync('createUser').access_token;
    var addr = wx.getStorageSync('addressETH');
    var $this = this;
    let money = $this.data.money 
    wallet.post('transaction/prepare', { access_token: token, coin_symbol: type, wallet_addr: addr }, function (res) {
      console.log(res)
      $this.setData({
        coinData: res.data,
       // money: money * res.data.exchange_rate,
        sliderSpeed: ((res.data.current - res.data.low) / (res.data.high - res.data.low)) * 100,
        current: res.data.current
      })
    }) 
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let $this = this
    let lang = wx.getStorageSync('lang')
    //let linkPer = wx.getStorageSync('userMessage');
    wx.getStorage({
      key: 'coinType',
      success: function (res) {
        if(res.data){
          $this.setData({
            coinMess: res.data || '',
            lang:lang
            //linkPer:linkPer.name,
            //qrCode:linkPer.wallet_addr
          })
          let yuE = lang =='en'?'balance':'余额'
          wx.setNavigationBarTitle({
            title: res.data.type + yuE + res.data.balance
          })
          switch(res.data.type){
            case 'BTC':
              $this.getBTCData && $this.getBTCData(res.data.type)
            break;
            case 'ETH':
              $this.getmoneyData && $this.getmoneyData(res.data.type)
            break;
            default:
              $this.tokenCoin && $this.tokenCoin(res.data.type)
            break;
          }
        
        }
       
      }
    })
   
  },
  closeFrame(){
    this.setData({
      fadeIn:false,
      arrData:[]
    })
  },
  Tocontact(){
   
      wx.setStorageSync('chooseKey', 0)
      wx.navigateTo({
        url: '../../myPages/contactsPage/contactsPage',
      })
  
  },
  goFee(){
    wx.navigateTo({
      url: './fee/fee',
    })
  },
  shuruEvent: function (ev) {
    //console.log(ev.detail.value.length);
    switch (ev.detail.value.length) {
      case 0:
        this.setData({
          arrData: []
        })
        break;
      case 1:
        this.setData({
          arrData: [0]
        })
        break;
      case 2:
        this.setData({
          arrData: [0, 1]
        })
        break;
      case 3:
        this.setData({
          arrData: [0, 1, 2]
        })
        break;
      case 4:
        this.setData({
          arrData: [0, 1, 2, 3]
        })
        break;
      case 5:
        this.setData({
          arrData: [0, 1, 2, 3, 4]
        })
        break;
      case 6:
        this.setData({
          arrData: [0, 1, 2, 3, 4, 5]
        })
        break;
      default:
        break;
    }
    this.setData({
      payPSWD: ev.detail.value
    })
    //console.log(ev.detail.value)
  },
  sliderChange(e){//矿工选项
    //console.log(e)
    var speed = e.detail.value/100;
    //console.log(speed)
    var low = this.data.coinData.low;
    var high = this.data.coinData.high;
    var val = (high-low)*speed+Number(low)
   //console.log(val)
    var gasLimit = this.data.coinData.gas
    this.setData({
      current:val
    })
   
  },
  sanCode(e){
    var $this = this;
   
        wx.scanCode({
          onlyFromCamera: true,
          success: (res) => {
            //console.log(res)
            var j = res.result
            //console.log(j)
            //console.log(j)
            $this.setData({
              qrCode: j,
              linkaddress:j
            })
          }
        })
   
  },
  inInfo:function(ev){//输入
    var id = ev.target.id
    var val = ev.detail.value
    var balance = this.data.coinData.balance;
    var rate = this.data.coinData.exchange_rate;
    let lang = this.data.lang;
    let goaddreFlag = this.data.goaddreFlag;
   switch(id){
     case 'linkicon'://币
     // console.log(val)
       if (Number(val) > Number(balance)) {
        // console.log(val)
         wx.showToast({
           title: lang == 'en' ? 'Insufficient balance' : '余额额度不够' ,
           icon: 'none',
           duration: 2000
         })
       } else {
         //console.log(111)
         var mon = val * rate;
         this.setData({
           money: goaddreFlag==true?mon:0,//资金转换
           coinNumber: val,
           'linkicon':val
         })
       }
     break;
     case 'linkaddress'://地址
       this.setData({
         //money: mon,
         'linkaddress': val,
          'qrCode':val
       })
     break;
     case 'linkcomment':
     this.setData({
       'linkcomment':val
     })
     break;
   }
   this.setData({
     transMon: id  ? 1 : 0
    })
  },
  addZore(str){
    let len = str.length;
    let nextLen = 64-len;
    let z = ''
    for(let i = 0;i<nextLen;i++){
      z +=0
    }
    return z + str
  },
  capacity() {//转代币
    var token = wx.getStorageSync('createUser').access_token;
    var coinType = wx.getStorageSync('coinType')
    var to = coinType.ram_token_addr;//合约地址
   // var to = '0xf79d7d43bbae5f64a8b2ef3bee7cc4cfbca5d4d7'
    var val = this.data.coinNumber
    // var gas = '0x52080'
    var gas =this.data.coinData.gas
    let current = this.data.current
    // let current = 0.0000041
    var gasPrice = '0x' + (parseInt((current * Math.pow(10, 18) / Number(gas)))).toString(16)
    //var gasPrice = this.data.coinData.gas_price
    // var gasPrice = '0x' + (41 * Math.pow(10, 9)).toString(16)
    var nonce = this.data.coinData.nonce;
    let toAddres = this.data.qrCode.substring(2)
    let addresLen = this.addZore(toAddres);
    //console.log(this.data.coinNumber)
    let num = Number(this.data.coinNumber*Math.pow(10,18)).toString(16)
    let data = '0x' + 'a9059cbb' + addresLen + this.addZore(num)
    console.log(data)
    var txParams = {
      nonce: nonce,
    gasPrice: gasPrice, //1 Gwei（= 1000000000 = 0x3B9ACA00）
      gasLimit: gas,
      // gasPrice: '0x'+(41*Math.pow(10,9)).toString(16),
      //gasLimit: '0x520809',
      to: to,
      // to: '0x7460f9d3ddb5a251c347381783740f2b06526ce3',//合约地址
      value: '0x00',
      //value:'0x00',
      data: data,
      // EIP 155 chainId --- mainnet: 1, ropsten: 3
      chainId: this.data.chainId
    }
    console.log(txParams)
    var miWord = wx.getStorageSync('pswd');
    var getWallet = wx.getStorageSync('walletKey');
    var hdwallet = wallet.decode && wallet.decode(miWord, getWallet);
    var raw = wallet.rawData(txParams, hdwallet)
    //console.log(raw)
    var params = {}
    params.access_token = token;
    params.coin_symbol = coinType.type;
    //params.raw = raw;
    params.raw = raw;
    params.wallet_addr = coinType.addre;
    params.gas_price = gasPrice;
    params.value = val;
    params.nonce = nonce;
    params.to = this.data.qrCode;
    params.gas = gas;
    params.data = data;
    //params.
    var $this = this;
    console.log(params);
    wallet.post('transaction/send', params, function (res) {
      console.log(res)
      if (res.code == 200) {
        $this.setData({
          fadeIn: false,
          arrData: []
        })
        wx.navigateBack({
          delta: 2
        })
        //wx.setStorageSync('exchangcoinflag', 1)
      }
    })
  },
  transferAccounts(){//eth转账接口
    var token = wx.getStorageSync('createUser').access_token;
    var addr = wx.getStorageSync('addressETH')
    var to = this.data.qrCode 
    var value = this.data.coinNumber
    var gas = this.data.coinData.gas
    var gasPrice ='0x'+parseInt((this.data.current *Math.pow(10,18) / Number(gas))).toString(16)
    var nonce = this.data.coinData.nonce;

    //let data = '路遥的小说，总是激荡人内心最深沉的情感，让人留恋，我想那就是生活，就算苦也是幸福的，无论是《平凡的世界》也好，还是《人生》也好，无一例外，那就是生活，生活中可以有爱情，可以没有爱情，爱情这个东西太梦幻，抓不住，但最能留住人的是亲情！生活是苦的，但一定有亲情，那就是幸福的！'
// let data = '00';
 var txParams={
      nonce: nonce,
      gasPrice:gasPrice, //1 Gwei（= 1000000000 = 0x3B9ACA00）
      gasLimit: gas,
      //gasLimit:0xf4240,//1000000
      to:to,
      // to: '0x7460f9d3ddb5a251c347381783740f2b06526ce3',//合约地址
      value: value*Math.pow(10,18),
      //value:'0x00',
     // data:'0x' + data,
     data:'',
     // data: '0x' + 'a9059cbb'+'' +'0000000000000000000000000000000000000000000000000000000000000001',
      // EIP 155 chainId --- mainnet: 1, ropsten: 3
      chainId: this.data.chainId
    }

    var miWord = wx.getStorageSync('pswd');
    var getWallet = wx.getStorageSync('walletKey');
    var hdwallet = wallet.decode && wallet.decode(miWord,getWallet);
    var raw = wallet.rawData(txParams,hdwallet)
    //console.log(raw)
    var params = {}
    params.access_token = token;
    params.coin_symbol = 'ETH';
    //params.raw = raw;
    params.raw = raw;
    params.wallet_addr = addr;
    params.gas_price = gasPrice;
    params.value = value;
    params.nonce = nonce;
    params.to = to;
    params.gas = gas;
   //params.
    var $this = this;
   // console.log(params);
    wallet.post('transaction/send', params, function (res) {
        console.log(res)
        if(res.code == 200){
          $this.setData({
            fadeIn:false,
            arrData:[]
          })
          wx.navigateBack({
            delta:2
          })
          //wx.setStorageSync('exchangcoinflag', 1)
        }
    })
  },
  transferBTC(){//btc转账；
    var pswd = wx.getStorageSync('pswd');
    var walletkey = wx.getStorageSync('walletKey');
    var hdwallet = wallet.decode(pswd,walletkey);
    var exchange = wallet.rawBTCDHash(hdwallet);
    var unspent = this.data.coinData.unspent || [];
    var icon = this.data.coinNumber
    //console.log(icon)
     unspent.sort(function(a,b){//small to big paixu
       return a.value_dec - b.value_dec;
     })
     //console.log(unspent);
     let len = unspent.length-1
     let unArr = [];
     var params = {
       coin_symbol: 'BTC'
     };
     params.access_token = wx.getStorageSync('createUser').access_token;
     params.wallet_addr = wx.getStorageSync('addressBTC');//转钱
     params.to = this.data.qrCode;//收钱地址
     params.value = icon//多少币
     //params.from = 
     params.fee = this.data.current.toFixed(5)//交易费
     params.data = ''
    //params.raw = ''//交易签名
     let val = 0
     console.log(this.data.current)
     if (icon > this.data.coinData.balance){
       wx.showToast({
         title: '余额不够',
         icon: 'none',
         duration: 2000
       })
     }else{
       if (icon > unspent[0].value_dec && icon <unspent[len].value_dec) {//bijiao
         unArr.push(unspent[len])
         let txb = exchange.txb;
         let address = exchange.sender.getAddress()
         console.log('address:'+address)
         txb.setVersion(1);
         txb.addInput(unspent[len].txid, unspent[len].tx_output_n);
         txb.addOutput(this.data.qrCode, icon * 100000000);// unspent[len].value_dec-icon-this.data.current
         let fee = unspent[len].value_dec - icon - this.data.current;
          txb.addOutput(address, parseInt(fee* 100000000));//0.01759-0.0001
         txb.sign(0, exchange.sender);
         params.raw=txb.build().toHex()
       } else if (icon < unspent[0].value_dec) {
         unArr.push(unspent[0])
         let sender = exchange.sender
         let txb = exchange.txb;
         let address = sender.getAddress()
         txb.setVersion(1);
         txb.addInput(unspent[0].txid, unspent[0].tx_output_n);
         txb.addOutput(this.data.qrCode, icon * 100000000);// unspent[0].value_dec-icon-this.data.current
         let fee = unspent[0].value_dec - icon - this.data.current;
         txb.addOutput(address, parseInt(fee * 100000000));//0.01759-0.0001
         txb.sign(0, sender);
         params.raw = txb.build().toHex()
       } else if (icon >= unspent[len].value_dec) {
         //icon>unspent最大值时，将每一项进行累加>icon，再跳出来
         let sender = exchange.sender
         let txb = exchange.txb;
         let address = sender.getAddress()
         txb.setVersion(1);
         unspent =  unspent.filter((res,index)=>{
                   // val += res.value_dec
                    if (val <= icon) {
                      txb.addInput(res.txid, res.tx_output_n);
                      return val += res.value_dec
                    }
            })
         
         txb.addOutput(this.data.qrCode, icon * 100000000);// unspent[0].value_dec-icon-this.data.current
         let fee = val - icon - this.data.current;
         txb.addOutput(address, parseInt(fee * 100000000));//0.01759-0.0001
          unspent.map(function(res,index){
            txb.sign(index, sender)
          })
         params.raw = txb.build().toHex()
         unArr = unspent;
      }
     }
     params.input = JSON.stringify(unArr)//input值 
     let   $this = this; 
    // console.log(params.fee)  
    // console.log(params)
      wallet.post('transactionbtc/send', params, function (res) {
        console.log(res)
       $this.setData({
         fadeIn: false,
         arrData: []
       })
       wx.navigateBack({
         delta: 2
       })
     })
  },
  commit(e) {//提交支付密码
    var pswd = wallet.MD5jiami(this.data.payPSWD)
    var localPswd = wx.getStorageSync('pswd');
    if(this.data.payPSWD == ''){
      wx.showToast({
        title: wx.T.locale == "zh-Hans" ? wx.T.locales['zh-Hans'].JLXXPropretyPaypswd : wx.T.locales['en'].JLXXPropretyPaypswd,
        icon: 'none',
        duration: 2000
      })
    }else{
      if (pswd == localPswd) {
        switch (this.data.coinMess.type){
              case 'BTC':
                this.transferBTC && this.transferBTC()
              break;
              case 'ETH':
                 this.transferAccounts && this.transferAccounts()
              break;
              default://智能合约转账
                  this.capacity && this.capacity()
              break;
        }
      
       //console.log('请求支付')
      }else{
        //console.log(1111)
        wx.showToast({
          title: wx.T.locale == "zh-Hans" ? wx.T.locales['zh-Hans'].paymentPassword : wx.T.locales['en'].paymentPassword,
          icon: 'none',
          duration: 2000
        })
      }
    }
   
  },
  affirmMoney:function(ev){//点击确认转账；
   if(this.data.transMon ==1){
    if (this.data.qrCode  == ''){
      wx.showToast({
        title: wx.T.locale == "zh-Hans" ? wx.T.locales['zh-Hans'].notAddress : wx.T.locales['en'].notAddress,
        icon: 'none',
        duration: 2000
      })
      } else if (this.data.coinNumber == ''){
      wx.showToast({
        title: wx.T.locale == "zh-Hans" ? wx.T.locales['zh-Hans'].notAmount : wx.T.locales['en'].notAmount,
        icon: 'none',
        duration: 2000
      })
    } else if (this.data.linkcomment == ''){
      wx.showToast({
        title: wx.T.locale == "zh-Hans" ? wx.T.locales['zh-Hans'].mustNotes : wx.T.locales['en'].mustNotes,
        icon: 'none',
        duration: 2000
      })
    }else{
      this.setData({
        fadeIn: this.data.transMon == 1 ? true : false
      })
    }
 
  } 
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      affirmLang: wx.T.locale == "zh-Hans" ? wx.T.locales['zh-Hans'] : wx.T.locales['en']

    })
    let linkPer = wx.getStorageSync('userMessage');
    let coinType = wx.getStorageSync('coinType')
    let chooseKey = wx.getStorageSync('chooseKey')
    
    if (coinType.type == linkPer.coin_symbol){
          if (!this.data.linkaddress) {
            //console.log(11)
            this.setData({
              qrCode: linkPer.wallet_addr || '',
              linkPer: linkPer.name || ''
            })
          }
        } else {
          wx.showToast({
            title:'地址币种选择有误',
            icon: 'none',
            duration: 2000
          })
        }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      linkaddress: ''
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})